<!-- src/components/CommentManagement.vue -->
<template>
  <div class="common-layout">
    <el-container>
      <!-- 顶部导航栏 -->
      <el-header class="header-container">
        <div class="logo">
          <img src="../img/yz.webp" alt="永泽游戏网" />
          <span class="yz">永泽游戏网 - 管理员后台</span>
        </div>
        <div class="header-right">
          <el-button type="danger" @click="logout">退出登录</el-button>
        </div>
      </el-header>

      <el-container>
        <!-- 左侧菜单栏 -->
        <el-aside width="200px">
          <el-scrollbar>
            <el-menu>
              <el-sub-menu index="1">
                <template #title>
                  <el-icon><setting /></el-icon>
                  <span>管理员功能</span>
                </template>
                <el-menu-item-group>
                  <el-menu-item index="1-1">
                    <router-link to="/checkGames">游戏管理</router-link>
                  </el-menu-item>
                  <el-menu-item index="1-2">
                    <router-link to="/home">通知公告管理</router-link>
                  </el-menu-item>
                  <el-menu-item index="1-3">
                    <router-link to="/user">用户管理</router-link>
                  </el-menu-item>
                  <el-menu-item index="1-4">
                    <router-link to="/category">游戏分类管理</router-link>
                  </el-menu-item>
                  <el-menu-item index="1-5">
                    <router-link to="/changeComments">评论管理</router-link>
                  </el-menu-item>
                </el-menu-item-group>
              </el-sub-menu>
            </el-menu>
          </el-scrollbar>
        </el-aside>

        <!-- 主内容区域 -->
        <el-main>
          <!-- 筛选和搜索 -->
          <el-form :inline="true" :model="filters" class="demo-form-inline">
            <el-form-item label="按游戏筛选">
              <el-select v-model="filters.game" placeholder="选择游戏" clearable @change="applyFilters">
                <el-option label="所有游戏" value="" />
                <el-option
                  v-for="game in games"
                  :key="game.id"
                  :label="game.name"
                  :value="game.name"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="按时间排序">
              <el-select v-model="filters.sort" placeholder="排序方式" @change="applyFilters">
                <el-option label="最新优先" value="desc" />
                <el-option label="最旧优先" value="asc" />
              </el-select>
            </el-form-item>
            <el-form-item label="搜索评论">
              <el-input v-model="filters.search" placeholder="输入关键词" clearable @input="applyFilters" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="applyFilters">应用筛选</el-button>
            </el-form-item>
          </el-form>

          <!-- 批量操作 -->
          <div class="bulk-actions">
            <el-button type="danger" @click="bulkDelete" :disabled="selectedComments.length === 0">
              批量删除
            </el-button>
          </div>

          <!-- 评论列表 -->
          <div class="comment-list">
            <div v-for="comment in comments" :key="comment.id" class="comment-card">
              <div class="comment-header">
                <div class="checkbox-wrapper">
                  <el-checkbox v-model="selectedComments" :label="comment.id" />
                  <span>{{ comment.userName }}</span> 在 <strong>{{ comment.name }}</strong> 发表评论
                </div>
                <span class="date">{{ formatDate(comment.createdAt) }}</span>
              </div>
              <div class="comment-body">
                <p>{{ comment.content.substring(0, 50) }}...</p>
                <el-button type="text" @click="toggleDetails(comment.id)">
                  {{ expandedComments.includes(comment.id) ? '收起详情' : '展开详情' }}
                </el-button>
              </div>
              <div class="comment-details" v-show="expandedComments.includes(comment.id)">
                <p><strong>完整评论：</strong>{{ comment.content }}</p>
              </div>
              <div class="comment-actions">
                <el-button type="danger" size="small" @click="deleteComment(comment.id)">删除</el-button>
              </div>
            </div>
          </div>

          <!-- 加载更多 -->
          <div class="load-more" v-if="hasMore">
            <el-button type="primary" @click="loadMoreComments">加载更多</el-button>
          </div>

          <!-- 删除确认模态框 -->
          <el-dialog v-model="showModal" title="确认删除" width="500" center>
            <span>确定要删除这条评论吗？</span>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="closeModal">取消</el-button>
                <el-button type="primary" @click="confirmDelete">删除</el-button>
              </div>
            </template>
          </el-dialog>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted,reactive } from 'vue';
import request from '../axios/request';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { computed } from 'vue';
import { useAuthStore } from '../stores/userStore';

const store = useAuthStore();
const token = localStorage.getItem('token');
const router = useRouter();
const pageKey = computed(() => {
  const storedPageKey = sessionStorage.getItem('pageKey');
  return storedPageKey || `${router.path || '/game'}-${Math.random().toString(36).substr(2, 9)}`;
});
// 状态定义
const comments = ref([]);
const hasMore = ref(true);
const expandedComments = ref([]);
const selectedComments = ref([]);
const filters = ref({
  game: '',
  sort: 'desc',
  search: ''
});
const games = ref([]);
const showModal = ref(false);
const commentToDelete = ref(null);
const pageNum = ref(1);
const pageSize = ref(15);
// 日期格式化
const formatDate = (date) => {
  return new Date(date).toLocaleString();
};

const fetchGames = async () => {
  try {
      const response = await request({
        url: `/game/list`,
        method: 'get',
        pageKey: pageKey.value,
      });
  
      if (response.data.code === 200) {
        games.value = response.data.data; // 假设返回数据结构为 { list: [], total: xx }
      } else {
        ElMessage.error('获取待审核游戏失败');
      }
    } catch (err) {
      console.error('请求失败:', err);
      ElMessage.error('请求失败，请重试');
    }
}

const formInline = reactive({
  user: ''
})

// 获取评论
const fetchComments = async () => {
  try {
      const response = await request({
        url: `/comment/listP`,
        method: 'post',
        data:{
        "pageSize": pageSize.value,
        "pageNum": pageNum.value,
        "game": filters.value.game,
        "sort": filters.value.sort,
        "search": filters.value.search
        },
        pageKey: pageKey.value,
      });
  
      if (response.data.code === 200) {
        comments.value = response.data.data; // 假设返回数据结构为 { list: [], total: xx }
      } else {
        ElMessage.error('获取待审核游戏失败');
      }
    } catch (err) {
      console.error('请求失败:', err);
      ElMessage.error('请求失败，请重试');
    }
};

// 加载更多评论
const loadMoreComments = async () => {
  pageNum.value++;
  await fetchComments();
};

// 切换详情展开/折叠
const toggleDetails = (commentId) => {
  if (expandedComments.value.includes(commentId)) {
    expandedComments.value = expandedComments.value.filter(id => id !== commentId);
  } else {
    expandedComments.value.push(commentId);
  }
};

// 置顶/取消置顶
const toggleTop = async (commentId, isTop) => {
  try {
    await axios.post('/comment/top', { commentId, isTop: !isTop });
    const index = comments.value.findIndex(c => c.id === commentId);
    if (index !== -1) comments.value[index].isTop = !isTop;
    ElMessage({
      message: isTop ? '取消置顶成功' : '置顶成功',
      type: 'success',
      plain: true
    });
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败');
  }
};

// 删除评论
const deleteComment = (commentId) => {
  commentToDelete.value = commentId;
  showModal.value = true;
};

// 确认删除
const confirmDelete = async () => {
  try {
      const response = await request({
        url: `/comment/delete?commentId=`+commentToDelete.value,
        method: 'delete',
        pageKey: pageKey.value,
      });
      if (response.data.code === 200) {
        fetchComments(); // 假设返回数据结构为 { list: [], total: xx }
        closeModal();
      } else {
        ElMessage.error('删除失败');
      }
    } catch (err) {
      console.error('请求失败:', err);
      ElMessage.error('请求失败，请重试');
    }
};

// 批量删除
const bulkDelete = async () => {
  if (selectedComments.value.length === 0) {
    ElMessage.warning('请选择要删除的评论');
    return;
  }
  try {
      const response = await request({
        url: `/comment/bulkDelete`,
        method: 'delete',
        pageKey: pageKey.value,
        data:selectedComments.value
      });
      if (response.data.code === 200) {
        fetchComments(); // 假设返回数据结构为 { list: [], total: xx }
      } else {
        ElMessage.error('删除失败');
      }
    } catch (err) {
      console.error('请求失败:', err);
      ElMessage.error('请求失败，请重试');
    }
};

 // 应用筛选
 const applyFilters = async () => {
  await fetchComments();
};

// 关闭模态框
const closeModal = () => {
  showModal.value = false;
  commentToDelete.value = null;
};

// 退出登录
const logout = () => {
  // 清除本地存储中的 token 或用户信息
  request({
    url: '/login/logout',
    method: 'get',
    pageKey: pageKey.value,
  })
    .then((res) => {
      if (res.data.code === 200) {
              // 提示用户退出成功
        ElMessage({
          message: '退出登录成功',
          type: 'success',
        });
        store.logout(pageKey.value);
        // 跳转到登录页面
        router.push('/');
      } else {
        ElMessage.error('退出登录失败');
      }
    })
    .catch((err) => {
      console.error(err);
      ElMessage.error('请求失败，请检查网络');
    });

};
  
// 初始化
onMounted(async () => {
  fetchComments();
  fetchGames();
});
</script>

<style scoped>
.common-layout {
  background: #f4f6f9;
  min-height: 100vh;
  padding-bottom: 50px;
}

.el-container {
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: #2c3e50;
  color: #fff;
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
}

.header-container .logo {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-container .logo img {
  height: 50px;
}

.header-container .yz {
  font-size: 1.5rem;
  font-weight: bold;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.el-aside {
  background-color: #fff;
  border-right: 1px solid #e6e6e6;
}

.el-menu {
  border: none;
}

.el-menu-item a {
  text-decoration: none;
  color: #303133;
}

.el-menu-item.is-active {
  background-color: #3498db;
  color: #fff;
}

.el-main {
  background: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
  margin: 20px;
}

.demo-form-inline {
  margin-bottom: 20px;
}

.el-form-item {
  margin-right: 15px;
}

.el-input,
.el-select {
  width: 200px;
}

.bulk-actions {
  margin-bottom: 20px;
}

.comment-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.comment-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #ddd;
}

.checkbox-wrapper {
  display: flex;
  align-items: center;
  gap: 10px;
}

.date {
  font-size: 12px;
  color: #666;
}

.comment-body {
  padding: 15px;
}

.comment-body p {
  margin: 0;
  color: #333;
}

.comment-details {
  background-color: #e9ecef;
  padding: 15px;
}

.comment-details p {
  margin: 5px 0;
  color: #444;
}

.comment-actions {
  padding: 10px;
  display: flex;
  gap: 10px;
}

.load-more {
  margin-top: 20px;
  text-align: center;
}

.el-button[type="primary"] {
  background-color: #3498db;
  border: none;
}

.el-button[type="primary"]:hover {
  background-color: #2980b9;
}

.el-button[type="danger"] {
  background-color: #e74c3c;
  border: none;
}

.el-button[type="danger"]:hover {
  background-color: #c0392b;
}

.el-button[type="warning"] {
  background-color: #f1c40f;
  border: none;
  color: #fff;
}

.el-button[type="warning"]:hover {
  background-color: #d4ac0d;
}

.el-dialog {
  border-radius: 10px;
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
}

.dialog-footer {
  text-align: center;
  padding: 15px;
}

.el-tag[type="success"] {
  background-color: #2ecc71;
}
</style>